package com.sch.www.user.controller;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sch.www.common.core.web.BaseController;
import com.sch.www.common.core.web.ResponseBean;
import com.sch.www.entity.SysUser;
import com.sch.www.user.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author admin
 * @since 2019-05-20
 */


@Api("用户信息管理")
@RestController
@RequestMapping(value = "/v1/user")
public class SysUserController extends BaseController {
    private static final PasswordEncoder encoder = new BCryptPasswordEncoder();

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysUserRoleService userRoleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysMenuService menuService;


    /**
     * 根据用户名获取用户详细信息
     *
     * @param username username
     * @return SysUserVo
     */
    @GetMapping("/findSysUserBySysUsername/{username}")
    @ApiOperation(value = "获取用户信息", notes = "根据用户name获取用户详细信息")
    @ApiImplicitParam(name = "username", value = "用户name", required = true, dataType = "String", paramType = "path")
    public SysUser findSysUserBySysUsername(@PathVariable String username) {
        SysUser user = userService.getByUsername(username);
        if (user != null) {
            if (user != null) {
                user.setRoles(roleService.listByUserId(user.getId()));
                user.setMenus(menuService.ListByUserId(user.getId()));
            }
        }
        return user;
    }

    /**
     * 根据id 获取
     *
     * @param id id
     * @return ResponseBean
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "获取用户信息", notes = "根据用户id获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String", paramType = "path")
    public ResponseBean<SysUser> user(@PathVariable String id) {
        SysUser user = null;
        if (StringUtils.isNotEmpty(id)) {
            user = userService.getById(id);
        }
        return new ResponseBean<>(user);
    }

//    /**
//     * 获取当前用户信息（角色、权限）
//     *
//     * @return 用户名
//     */
//    @GetMapping("/info")
//    @ApiOperation(value = "获取用户信息", notes = "获取当前登录用户详细信息")
//    public ResponseBean<SysUser> user(Principal principal) {
//        String username = principal.getName();
//        SysUser user = null;
//        if (StringUtils.isNotEmpty(username)) {
//            user = userService.getByUsername(username);
//            if (user!=null){
//                user.setRoles(roleService.listByUserId(user.getId()));
//                user.setMenus(roleService.)
//
//            }
//
//
//
//        }
//
//
//        SysUserVo userVo = new SysUserVo();
//        userVo.setSysUsername(principal.getName());
//        return new ResponseBean<>(userService.findSysUserInfo(userVo));
//    }
//

//
//    /**
//     * 获取分页数据
//     *
//     * @param pageNum  pageNum
//     * @param pageSize pageSize
//     * @param sort     sort
//     * @param order    order
//     * @param userVo   userVo
//     * @return PageInfo
//     * @author tangyi
//     * @date 2018/8/26 22:56
//     */
//    @RequestMapping("userList")
//    @ApiOperation(value = "获取用户列表")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = CommonConstant.PAGE_NUM, value = "分页页码", defaultValue = CommonConstant.PAGE_NUM_DEFAULT, dataType = "String"),
//            @ApiImplicitParam(name = CommonConstant.PAGE_SIZE, value = "分页大小", defaultValue = CommonConstant.PAGE_SIZE_DEFAULT, dataType = "String"),
//            @ApiImplicitParam(name = CommonConstant.SORT, value = "排序字段", defaultValue = CommonConstant.PAGE_SORT_DEFAULT, dataType = "String"),
//            @ApiImplicitParam(name = CommonConstant.ORDER, value = "排序方向", defaultValue = CommonConstant.PAGE_ORDER_DEFAULT, dataType = "String"),
//            @ApiImplicitParam(name = "userVo", value = "用户信息", dataType = "SysUserVo")
//    })
//    public PageInfo<SysUser> userList(@RequestParam(value = CommonConstant.PAGE_NUM, required = false, defaultValue = CommonConstant.PAGE_NUM_DEFAULT) String pageNum,
//                                      @RequestParam(value = CommonConstant.PAGE_SIZE, required = false, defaultValue = CommonConstant.PAGE_SIZE_DEFAULT) String pageSize,
//                                      @RequestParam(value = CommonConstant.SORT, required = false, defaultValue = CommonConstant.PAGE_SORT_DEFAULT) String sort,
//                                      @RequestParam(value = CommonConstant.ORDER, required = false, defaultValue = CommonConstant.PAGE_ORDER_DEFAULT) String order,
//                                      @RequestParam(value = "username", required = false, defaultValue = "") String username,
//                                      SysUserVo userVo) {
//        SysUser user = new SysUser();
//        BeanUtils.copyProperties(userVo, user);
//        // 用户名查询条件
//        user.setSysUsername(username);
//        PageInfo<SysUser> page = userService.findPage(PageUtil.pageInfo(pageNum, pageSize, sort, order), user);
//        List<SysUser> users = page.getList();
//        if (CollectionUtils.isNotEmpty(users)) {
//            Dept dept = new Dept();
//            // 流处理获取部门ID集合，转成字符串数组
//            dept.setIds(users.stream().filter(tempSysUser -> tempSysUser.getDeptId() != null).map(SysUser::getDeptId).distinct().toArray(String[]::new));
//            // 批量查找部门
//            List<Dept> deptList = deptService.findListById(dept);
//            // 流处理获取用户ID集合，根据用户ID批量查找角色
//            List<SysUserRole> userRoles = userRoleService.getBySysUserIds(users.stream().map(SysUser::getId).collect(Collectors.toList()));
//            List<Role> roleList = new ArrayList<>();
//            if (CollectionUtils.isNotEmpty(userRoles)) {
//                Role role = new Role();
//                // 获取角色ID集合，转成字节数组
//                role.setIds(userRoles.stream().map(SysUserRole::getRoleId).distinct().toArray(String[]::new));
//                // 批量查找角色
//                roleList = roleService.findListById(role);
//            }
//            // 遍历用户集合，设置部门、角色
//            List<Role> finalRoleList = roleList;
//            users.forEach(tempSysUser -> {
//                // 设置部门信息
//                if (CollectionUtils.isNotEmpty(deptList)) {
//                    // 用户所属部门
//                    Dept userDept = deptList.stream()
//                            // 按部门ID找到部门信息
//                            .filter(tempDept -> tempDept.getId().equals(tempSysUser.getDeptId()))
//                            .findFirst().orElse(null);
//                    if (userDept != null) {
//                        tempSysUser.setDeptName(userDept.getDeptName());
//                        tempSysUser.setDeptId(userDept.getId());
//                    }
//                }
//                // 设置角色信息
//                if (CollectionUtils.isNotEmpty(userRoles)) {
//                    List<Role> userRoleList = new ArrayList<>();
//                    userRoles.stream()
//                            // 过滤
//                            .filter(tempSysUserRole -> tempSysUser.getId().equals(tempSysUserRole.getSysUserId()))
//                            .forEach(tempSysUserRole -> finalRoleList.stream()
//                                    .filter(role -> role.getId().equals(tempSysUserRole.getRoleId()))
//                                    .forEach(userRoleList::add));
//                    tempSysUser.setRoleList(userRoleList);
//                }
//            });
//        }
//        return page;
//    }
//
//    /**
//     * 创建用户
//     *
//     * @param userDto userDto
//     * @return ResponseBean
//     * @author tangyi
//     * @date 2018/8/26 14:34
//     */
//    @PostMapping
//    @PreAuthorize("hasAuthority('sys:user:add') or hasAnyRole('" + SecurityConstant.ROLE_ADMIN + "', '" + SecurityConstant.ROLE_TEACHER + "')")
//    @ApiOperation(value = "创建用户", notes = "创建用户")
//    @ApiImplicitParam(name = "userDto", value = "用户实体user", required = true, dataType = "SysUserDto")
//    @Log("新增用户")
//    public ResponseBean<Boolean> addSysUser(@RequestBody SysUserDto userDto) {
//        SysUser user = new SysUser();
//        BeanUtils.copyProperties(userDto, user);
//        user.setCommonValue(SecurityUtil.getCurrentSysUsername(), SysUtil.getSysCode());
//        // 设置默认密码
//        if (StringUtils.isEmpty(userDto.getPassword()))
//            userDto.setPassword(CommonConstant.DEFAULT_PASSWORD);
//        user.setPassword(encoder.encode(userDto.getPassword()));
//        // 保存用户
//        return new ResponseBean<>(userService.insert(user) > 0);
//    }
//
//    /**
//     * 更新用户
//     *
//     * @param userDto userDto
//     * @return ResponseBean
//     * @author tangyi
//     * @date 2018/8/26 15:06
//     */
//    @PutMapping
//    @PreAuthorize("hasAuthority('sys:user:edit') or hasAnyRole('" + SecurityConstant.ROLE_ADMIN + "', '" + SecurityConstant.ROLE_TEACHER + "')")
//    @ApiOperation(value = "更新用户信息", notes = "根据用户id更新用户的基本信息、角色信息")
//    @ApiImplicitParam(name = "userDto", value = "用户实体user", required = true, dataType = "SysUserDto")
//    @Log("修改用户")
//    public ResponseBean<Boolean> updateSysUser(@RequestBody SysUserDto userDto) {
//        try {
//            return new ResponseBean<>(userService.updateSysUser(userDto));
//        } catch (Exception e) {
//            logger.error("更新用户信息失败！", e);
//        }
//        return new ResponseBean<>(Boolean.FALSE);
//    }
//
//    /**
//     * 更新用户的基本信息
//     *
//     * @param userDto userDto
//     * @return ResponseBean
//     * @author tangyi
//     * @date 2018/10/30 10:06
//     */
//    @PutMapping("/updateInfo")
//    @ApiOperation(value = "更新用户基本信息", notes = "根据用户id更新用户的基本信息")
//    @ApiImplicitParam(name = "userDto", value = "用户实体user", required = true, dataType = "SysUserDto")
//    @Log("更新用户基本信息")
//    public ResponseBean<Boolean> updateInfo(@RequestBody SysUserDto userDto) {
//        // 新密码不为空
//        if (StringUtils.isNotEmpty(userDto.getNewPassword())) {
//            if (!encoder.matches(userDto.getOldPassword(), userDto.getPassword())) {
//                return new ResponseBean<>(Boolean.FALSE, "新旧密码不匹配");
//            } else {
//                // 新旧密码一致，修改密码
//                userDto.setPassword(encoder.encode(userDto.getNewPassword()));
//            }
//        }
//        return new ResponseBean<>(userService.update(userDto) > 0);
//    }
//
//    /**
//     * 删除用户
//     *
//     * @param id id
//     * @return ResponseBean
//     * @author tangyi
//     * @date 2018/8/26 15:28
//     */
//    @DeleteMapping("/{id}")
//    @PreAuthorize("hasAuthority('sys:user:del') or hasAnyRole('" + SecurityConstant.ROLE_ADMIN + "', '" + SecurityConstant.ROLE_TEACHER + "')")
//    @ApiOperation(value = "删除用户", notes = "根据ID删除用户")
//    @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path")
//    @Log("删除用户")
//    public ResponseBean<Boolean> deleteSysUser(@PathVariable String id) {
//        try {
//            SysUser user = userService.get(id);
//            user.setCommonValue(SecurityUtil.getCurrentSysUsername(), SysUtil.getSysCode());
//            userService.delete(user);
//        } catch (Exception e) {
//            logger.error("删除用户信息失败！", e);
//        }
//        return new ResponseBean<>(Boolean.FALSE);
//    }
//
//    /**
//     * 导出
//     *
//     * @param userVo userVo
//     * @author tangyi
//     * @date 2018/11/26 22:11
//     */
//    @PostMapping("/export")
//    @PreAuthorize("hasAuthority('sys:user:export') or hasAnyRole('" + SecurityConstant.ROLE_ADMIN + "', '" + SecurityConstant.ROLE_TEACHER + "')")
//    @ApiOperation(value = "导出用户", notes = "根据用户id导出用户")
//    @ApiImplicitParam(name = "userVo", value = "用户信息", required = true, dataType = "SysUserVo")
//    @Log("导出用户")
//    public void exportSysUser(@RequestBody SysUserVo userVo, HttpServletRequest request, HttpServletResponse response) {
//        try {
//            // 配置response
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("multipart/form-data");
//            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, Servlets.getDownName(request, "用户信息" + new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date()) + ".xlsx"));
//            List<SysUser> users;
//            if (StringUtils.isNotEmpty(userVo.getIdString())) {
//                SysUser user = new SysUser();
//                // 按逗号切割ID，流处理获取ID集合，去重，转成字符串数组
//                user.setIds(Stream.of(userVo.getIdString().split(",")).filter(StringUtils::isNotBlank).distinct().toArray(String[]::new));
//                users = userService.findListById(user);
//            } else {    // 导出全部用户
//                users = userService.findList(new SysUser());
//            }
//            ExcelToolUtil.exportExcel(request.getInputStream(), response.getOutputStream(), MapUtil.java2Map(users), SysUserUtils.getSysUserMap());
//        } catch (Exception e) {
//            logger.error("导出用户数据失败！", e);
//        }
//    }
//
//    /**
//     * 导入数据
//     *
//     * @param file file
//     * @return ResponseBean
//     * @author tangyi
//     * @date 2018/11/28 12:44
//     */
//    @RequestMapping("import")
//    @PreAuthorize("hasAuthority('sys:user:import') or hasAnyRole('" + SecurityConstant.ROLE_ADMIN + "', '" + SecurityConstant.ROLE_TEACHER + "')")
//    @ApiOperation(value = "导入数据", notes = "导入数据")
//    @Log("导入用户")
//    public ResponseBean<Boolean> importSysUser(@ApiParam(value = "要上传的文件", required = true) MultipartFile file, HttpServletRequest request) {
//        try {
//            logger.debug("开始导入用户数据");
//            List<SysUser> users = MapUtil.map2Java(SysUser.class,
//                    ExcelToolUtil.importExcel(file.getInputStream(), SysUserUtils.getSysUserMap()));
//            if (CollectionUtils.isNotEmpty(users)) {
//                for (SysUser user : users) {
//                    if (userService.update(user) < 1)
//                        userService.insert(user);
//                }
//            }
//            return new ResponseBean<>(Boolean.TRUE);
//        } catch (Exception e) {
//            logger.error("导入用户数据失败！", e);
//        }
//        return new ResponseBean<>(Boolean.FALSE);
//    }
//
//    /**
//     * 批量删除
//     *
//     * @param user user
//     * @return ResponseBean
//     * @author tangyi
//     * @date 2018/12/4 9:58
//     */
//    @PostMapping("/deleteAll")
//    @PreAuthorize("hasAuthority('sys:user:del') or hasAnyRole('" + SecurityConstant.ROLE_ADMIN + "', '" + SecurityConstant.ROLE_TEACHER + "')")
//    @ApiOperation(value = "批量删除用户", notes = "根据用户id批量删除用户")
//    @ApiImplicitParam(name = "user", value = "用户信息", dataType = "SysUser")
//    @Log("批量删除用户")
//    public ResponseBean<Boolean> deleteAllSysUsers(@RequestBody SysUser user) {
//        boolean success = false;
//        try {
//            if (StringUtils.isNotEmpty(user.getIdString()))
//                success = userService.deleteAll(user.getIdString().split(",")) > 0;
//        } catch (Exception e) {
//            logger.error("删除用户失败！", e);
//        }
//        return new ResponseBean<>(success);
//    }
//
//    /**
//     * 根据ID查询
//     *
//     * @param userVo userVo
//     * @return ResponseBean
//     * @author tangyi
//     * @date 2018/12/31 21:16
//     */
//    @RequestMapping(value = "/findById", method = RequestMethod.POST)
//    @ApiOperation(value = "根据ID查询用户", notes = "根据ID查询用户")
//    @ApiImplicitParam(name = "userVo", value = "用户信息", required = true, paramType = "SysUserVo")
//    public ResponseBean<List<SysUserVo>> findById(@RequestBody SysUserVo userVo) {
//        ResponseBean<List<SysUserVo>> returnT = null;
//        SysUser user = new SysUser();
//        user.setIds(userVo.getIds());
//        Stream<SysUser> userStream = userService.findListById(user).stream();
//        if (Optional.ofNullable(userStream).isPresent()) {
//            List<SysUserVo> userVoList = userStream.map(tempSysUser -> {
//                SysUserVo tempSysUserVo = new SysUserVo();
//                BeanUtils.copyProperties(tempSysUser, tempSysUserVo);
//                return tempSysUserVo;
//            }).collect(Collectors.toList());
//            returnT = new ResponseBean<>(userVoList);
//        }
//        return returnT;
//    }
//
//    /**
//     * 注册
//     *
//     * @param userDto userDto
//     * @return ResponseBean
//     * @author tangyi
//     * @date 2019/01/10 22:35
//     */
//    @ApiOperation(value = "注册", notes = "注册")
//    @ApiImplicitParam(name = "userDto", value = "用户实体user", required = true, dataType = "SysUserDto")
//    @PostMapping("register")
//    @Log("注册用户")
//    public ResponseBean<Boolean> register(SysUserDto userDto) {
//        boolean success = false;
//        SysUser user = new SysUser();
//        BeanUtils.copyProperties(userDto, user);
//        user.setCommonValue(SecurityUtil.getCurrentSysUsername(), SysUtil.getSysCode());
//        // 设置默认密码
//        if (StringUtils.isEmpty(userDto.getPassword()))
//            userDto.setPassword(CommonConstant.DEFAULT_PASSWORD);
//        user.setPassword(encoder.encode(userDto.getPassword()));
//        user.setStatus(CommonConstant.DEL_FLAG_NORMAL.toString());
//        // 保存用户
//        if (userService.insert(user) > 0) {
//            // 分配默认角色
//            Role role = new Role();
//            role.setIsDefault(RoleConstant.IS_DEFAULT_ROLE);
//            // 查询默认角色
//            Stream<Role> roleStream = roleService.findList(role).stream();
//            if (Optional.ofNullable(roleStream).isPresent()) {
//                Role defaultRole = roleStream.findFirst().orElse(null);
//                if (defaultRole != null) {
//                    SysUserRole userRole = new SysUserRole();
//                    userRole.setCommonValue(SecurityUtil.getCurrentSysUsername(), SysUtil.getSysCode());
//                    userRole.setSysUserId(user.getId());
//                    userRole.setRoleId(defaultRole.getId());
//                    // 保存用户角色关系
//                    success = userRoleService.insert(userRole) > 0;
//                }
//            }
//        }
//        return new ResponseBean<>(success);
//    }


}
